package com.jzt.gateway.filter;

import com.jzt.gateway.GlobalConstant;
import com.jzt.gateway.utils.ExchangeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/07/06 15:59 <br/>
 */
@Component
@Slf4j
public class ClearHeaderGlobalFilter implements GlobalFilter, Ordered {
    private static final int Order = Integer.MAX_VALUE - 1;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 需要确保 GlobalConstant.GATEWAY_AUTH_TOKEN_NAME 请求头正常透传(授权处理成功才透传)
        Boolean isExecSuccess = exchange.getAttributeOrDefault(GlobalConstant.AUTHENTICATION_EXEC_ATTR, false);
        if (!isExecSuccess) {
            exchange = ExchangeUtils.modifyRequestHeaders(exchange, exchange.getRequest());
            ServerHttpRequest request = exchange.getRequest();
            request.getHeaders().remove(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME);
            request.getHeaders().remove(GlobalConstant.GATEWAY_USER_AGENT_ID_NAME);
            request.getHeaders().remove(GlobalConstant.GATEWAY_ONE_ID_NAME);
            List<String> cookies = request.getHeaders().get(HttpHeaders.COOKIE);
            if (cookies == null) {
                cookies = new ArrayList<>();
            }
            cookies = cookies.stream()
                    .filter(value -> value == null || !value.toLowerCase().startsWith(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME + "="))
                    .collect(Collectors.toList());
            request.getHeaders().put(HttpHeaders.COOKIE, cookies);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Order;
    }
}
